<script lang="tsx">
import {defineComponent, nextTick, onMounted, ref, watch} from "vue";
import {ElTreeSelect} from "element-plus"
import {SelectUserProps, selectUserProps} from "/@/components/Business/SelectUserTree/ts";
import {listUserTreeByOrgId} from "/@/api/system/UserApi";
import {useUserStore} from "/@/store/modules/user";
import BaseIcon from '/@/components/Base/BaseIcon/index.vue'
export default defineComponent({
  name: "SelectUserTree",
  props: selectUserProps,
  setup(props: SelectUserProps, {expose, emit, slots}) {
    const options = ref<any[]>([])
    const disabledHandler = (value,c) => {
       if(value.type === 'org'){
          return true;
       }else if (value.disabled) {
         return  true;
       }
       return  false;
    }

    const propsParams = {
      label: 'name',
      children: 'children',
      disabled: disabledHandler

    }
    const value = ref()
    watch(
        () => props.modelValue,
        (newValue) => {
          value.value = newValue
        },
        {deep: true, immediate: true}
    );
    watch(
        () => value.value,
        (newValue) => {
          emit("update:modelValue", newValue)
        },
        {deep: true}
    );
    const initUserList = async () => {
      let orgId = "0"
      if (props.scope === 'current') {
        let userStore = useUserStore();
        orgId = userStore.orgId
      }
      options.value = await listUserTreeByOrgId(orgId)
    }
    onMounted(() => {
      initUserList()
    })

    const render = () => {
      let keys = [] as any[]
      if (props.modelValue) {
        if (props.modelValue instanceof Array) {
          keys = props.modelValue
        } else {
          keys = [props.modelValue]
        }
      }
      return <ElTreeSelect multiple={props.multiple} show-checkbox={props.multiple} v-model={value.value} check-strictly={true} default-expanded-keys={keys} class="w-full"
                           node-key="id" props={propsParams} data={options.value}>
        {{
          default: ({ node, data })=> {
            if (data.type == 'org') {
              return <div class="flex">
                <BaseIcon icon="icons:clarity:flow-chart-line" class="mr-1.5"></BaseIcon>
                <span>{data.name}</span>
              </div>
            } else {
            return  <div class="flex">
                <BaseIcon icon="icons:clarity:user-line" class="mr-1.5"></BaseIcon>
                <span>{data.name}</span>
              </div>
            }
          }

        }}
      </ElTreeSelect>
    }
    return render
  }
})
</script>

<style scoped>

</style>